package org.puppet.demo.tank.control;

import org.puppet.demo.tank.puppet.Tank;
import org.puppet.game.base.PuppetUtils;
import org.puppet.game.control.AbstractController;
import org.puppet.game.control.PuppetUpdateController;
import org.puppet.game.control.TouchController;

public class TankController extends AbstractController {

	private TouchController touchHandler;

	private boolean ctrlPlayer = false;
	private Tank tank;
	private float defaultAccY = -0.0028f;

	private float speedFix = 650f;
	private float minY = 0f;
	private float maxY = 160f;
	private float minX = 0f;
	private float maxX =319f;
	
	public TankController(Tank tank) {
		this.tank = tank;
	}

	public boolean action(Integer eventId, Object e) {
		if(eventId.equals(PuppetUpdateController.IN_WORLD)){
			inWorld(e);
		} else if (eventId.equals(TouchController.EVENT_DOWN)) {
			touchHandler = (TouchController) e;
			onTouchDown();
		} else if (eventId.equals(TouchController.EVENT_UP)) {
			touchHandler = (TouchController) e;
			onTouchUp();
		}
		return true;
	}

	private void inWorld(Object e) {

		if (tank.x < minX) {
			tank.x = minX ;
			if(tank.isWalking()){
				tank.stand();
			}
		}if (tank.x > maxX) {
			tank.x = maxX ;
			if(tank.isWalking()){
				tank.stand();
			}
		}
		if (tank.y > maxY) {
			tank.y = maxY;
			tank.stand();
		} else {
			minY=tank.getHeight();
			if (tank.y < minY) {
				tank.y = minY;
				tank.vY = 0.0f;
			}
		}
		
	}

	public boolean onTouchDown() {
		ctrlPlayer = PuppetUtils.pointInRect(touchHandler.getFirstPoint(), tank.getLeft(), tank.getTop(), tank.getWidth(), tank.getHeight());
		if (!ctrlPlayer) {
			float xv = 0.3f;
			if (touchHandler.getX() < tank.x) {
				xv = 0 - xv;
			}
			tank.walk(xv, 0);
		}
		return true;
	}

	public boolean onTouchUp() {
		if (!ctrlPlayer && tank.isWalking()) {
			tank.stand();
		}
		if (ctrlPlayer) {
			tank.acceY = defaultAccY;
			tank.shoot(1, (float) (touchHandler.getVelocityX() / speedFix), (float) (touchHandler.getVelocityY() / speedFix));
			ctrlPlayer = false;
		}

		return true;
	}

	public int[] lookEvent() {
		return new int[]{TouchController.EVENT_DOWN, TouchController.EVENT_UP, PuppetUpdateController.IN_WORLD};
	}
	
}
